﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using EKETEAM.Data;
using EKETEAM.FrameWork;
using LitJson;

namespace eFrameWork.Plugins
{
    public partial class ProUpload : System.Web.UI.Page
    {
        public string formhost = "";
        private bool writeLog = true;
        public bool isMobile = false;
        private string tempPath = "";//临时文件夹
        private string backPath = "";//返回路径
        private string sourcePath = "";//源文件路径
        private string basePath = ""; //根目录
        public bool piceidtonline = false;
        public string obj = eParameters.QueryString("obj");
        protected void Page_Load(object sender, EventArgs e)
        {
            basePath = eRunTime.basePath;
            tempPath = eRunTime.tempPath;
            backPath = eRunTime.tempURL;
            sourcePath = eRunTime.sourcePathCurrent;
            piceidtonline = Directory.Exists(Server.MapPath("~/Plugins/pictureeditor/"));



            #region 文件类型检查
            if (Request.Files.Count > 0)
            {
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    HttpPostedFile file = Request.Files[i];
                    string ext = file.FileName.fileExtension();
                    if(!eConfig.allowExtensions.Contains(ext))
                    {
                        if (Request.UrlReferrer != null && Request.UrlReferrer.PathAndQuery.ToLower().IndexOf("plugins/proupload.aspx") > -1)
                        {
                            Response.Write("<div style=\"font-size:12px;color:#ff0000;\">文件类型不允许上传!&nbsp;&nbsp;<a href=\"javascript:;\" style=\"color:#1F47F4;text-decoration:none;\" onclick=\"history.back();\">返回</a></div>");
                            Response.End();
                        }
                        else
                        {
                        }
                        eResult.Error("文件类型不允许上传!");
                    }
                }
            }
            #endregion
            string userAgent = HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"].ToString().Replace(" ", "").ToLower();
            if (userAgent.IndexOf(";android") > -1 || userAgent.IndexOf("android;") > -1 || userAgent.IndexOf("iphone;") > -1 || userAgent.IndexOf("ipad;") > -1)
            {
                isMobile = true;
                imgFile.Attributes.Add("style", "width:90px;overflow:hidden;");
            }
            else
            {
                imgFile.Attributes.Add("style", "width:152px;overflow:hidden;");
            }
            imgFile.Attributes.Add("preventexts",eConfig.PreventExtensions.ToString());

            string accUrl = eConfig.AccessorysURL();
            #region 安全性检查
            //1.WebAPI用户放行
            //2.同一来源放行
            //3.来源被授权时放行
            if (Request.Headers["auth"] != null) //WebAPI访问
            {
                string auth = Request.Headers["auth"].ToString();
                eToken token = new eToken(auth);
                eUser user = new eUser(token);
            }
            else
            {

                if (eUser.Areas.Count == 0) eResult.Error("1012", "访问未被许可!");
                if (Request.UrlReferrer == null) //无来源页面
                {
                    eResult.Error("1012", "访问未被许可!");
                }
                else
                {

                    if (Request.Url.Host.ToLower() != Request.UrlReferrer.Host.ToLower() && accUrl.ToLower().IndexOf(Request.UrlReferrer.Host.ToLower()) == -1) //不是同一站点访问
                    {
                        DataRow[] rows = eBase.a_eke_sysAllowDomain.Select("Domain='" + Request.UrlReferrer.Host + "'");
                        if (rows.Length == 0)
                        {
                            JsonData json = new JsonData();
                            json.Add("domain", Request.UrlReferrer.Host);

                            eTable tb = new eTable("a_eke_sysErrors");
                            tb.Fields.Add("URL", Request.UrlReferrer.AbsoluteUri);
                            tb.Fields.Add("Message", "未授权访问!");
                            tb.Fields.Add("StackTrace", json.ToJson());
                            tb.Add();

                            eResult.Error("1012", "访问未被许可!");
                        }
                    }
                }
            }

            if (Request.UrlReferrer != null)
            {
                if (Request.UrlReferrer.Host.ToLower() != Request.Url.Host.ToLower())
                {
                    formhost = Request.UrlReferrer.Host.ToString();
                }
            }
            #endregion
            int PictureMaxWidth = 0;
            if (Request.QueryString["PictureMaxWidth"] != null) PictureMaxWidth = Convert.ToInt32(Request.QueryString["PictureMaxWidth"]);
            if (Request.QueryString["MaxWidth"] != null) PictureMaxWidth = Convert.ToInt32(Request.QueryString["MaxWidth"]);

            int ThumbWidth = 0;
            if (Request.QueryString["ThumbWidth"] != null) ThumbWidth = Convert.ToInt32(Request.QueryString["ThumbWidth"]);
            #region 编辑器上传文件
            if (Request.QueryString["postdata"] != null)
            {
                /*
                string postdata = Request.QueryString["postdata"].ToString();
                postdata = HttpUtility.UrlDecode(postdata);
                postdata = postdata.Replace("0x2f", "/").Replace("0x2b", "+").Replace("0x20", " ");
                Response.Write(postdata);
                */
                Response.End();
            }
            if (Request.QueryString["type"] != null)
            {
                #region API上传附件
                if (Request.QueryString["type"].ToLower() == "file")
                {
                    JsonData json = new JsonData();
                    json.Add("errcode", "0");
                    json.Add("message", "请求成功!");
                    json["files"] = JsonMapper.ToObject("[]");
                    for (int i = 0; i < Request.Files.Count; i++)
                    {
                        HttpPostedFile file = Request.Files[i];
                        string ext = file.FileName.fileExtension();
                        string filename = eBase.GetFileName() + ext;
                        string pathname = tempPath + filename;
                        while (File.Exists(pathname))
                        {
                            filename = eBase.GetFileName() + ext;
                            pathname = tempPath + filename;
                        }
                        if (!Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath);
                        file.safeSaveAs(pathname);
                        if (eConfig.saveSource())
                        {
                            if (!Directory.Exists(sourcePath)) Directory.CreateDirectory(sourcePath);
                            string _pathname = sourcePath + filename;
                            file.safeSaveAs(_pathname);
                        }

                        string size = file.Size();
                        if (PictureMaxWidth > 0 && ".bmp.jpg.gif.jpeg.png".IndexOf(ext) > -1)
                        {
                            filename = ePicture.AutoHandle(pathname, PictureMaxWidth);
                            pathname = tempPath + filename;//jpeg,bmp会处理成jpg
                            FileInfo fi = new FileInfo(pathname);
                            size = fi.Size();
                        }

                        eFileInfo finfo = new eFileInfo(filename);


                        filename = backPath + filename;
                        JsonData item = new JsonData();
                        item.Add("name", file.FileName);
                        item.Add("ext", ext);
                        item.Add("size", size);
                        item.Add("time", string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now));
                        item.Add("url", filename);
                        json["files"].Add(item);
                    }
                    // eBase.WriteJson(json);//IE解析有问题：文档的顶层无效
                    Response.Clear();
                    Response.Write(json.ToJson());
                    Response.End();
                }
                #endregion
                #region 编辑器-图片上传
                //string allExt = ".gif.jpg.jpeg.bmp.png";
                if (Request.QueryString["type"].ToLower() == "image")
                {
                    if (Request.Files.Count == 0) showError("请选择文件!");
                    JsonData json = new JsonData();
                    json.Add("errcode", "0");
                    json.Add("message", "请求成功!");
                    json["files"] = JsonMapper.ToObject("[]");

                    //string filenames = "";
                    for (int i = 0; i < Request.Files.Count; i++)
                    {
                        HttpPostedFile file = Request.Files[i];   
                        string ext = file.FileName.fileExtension();

                        string filename = eBase.GetFileName() + ext;
                        string pathname = tempPath + filename;
                        while (File.Exists(pathname))
                        {
                            filename = eBase.GetFileName() + ext;
                            pathname = tempPath + filename;
                        }
                        if (!Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath);
                        file.safeSaveAs(pathname);
                        if (eConfig.saveSource())
                        {
                            if (!Directory.Exists(sourcePath)) Directory.CreateDirectory(sourcePath);
                            string _pathname = sourcePath + filename;
                            file.safeSaveAs(_pathname);
                        }

                        filename = ePicture.AutoHandle(pathname, PictureMaxWidth);
                        eFileInfo finfo = new eFileInfo(filename);
                        #region 缩略图
                        if (ThumbWidth > 0 && !eConfig.allowExtensions.Contains(finfo.fileExtension))
                        {
                            pathname = tempPath + filename;
                            eFileInfo fi = new eFileInfo(tempPath + filename);
                            string thumbpathname = tempPath + fi.Name + "_thumb" + fi.fileExtension;
                            System.IO.File.Copy(pathname, thumbpathname);
                            ePicture.ToWidth(thumbpathname, ThumbWidth);

                            filename = backPath + fi.Name + "_thumb" + fi.fileExtension;
                        }
                        else
                        {
                            filename = backPath + filename;
                        }
                        #endregion
                        #region 日志
                        if (writeLog)
                        {
                            eTable etb = new eTable("a_eke_sysErrors");
                            etb.Fields.Add("Message", "upload");
                            JsonData _json = new JsonData();
                            _json.Add("filename", file.FileName);
                            _json.Add("size", file.ContentLength.ToString());
                            _json.Add("path", "upload/" + string.Format("{0:yyyy/MM/dd}", DateTime.Now) + "/" + filename);
                            etb.Fields.Add("StackTrace", _json.ToJson());
                            //etb.Add();
                        }
                        #endregion

                        //if (filenames.Length > 0) filenames += ";";
                        //filenames += filename;
                        JsonData item = new JsonData();
                        item.Add("url", filename);
                        json["files"].Add(item);
                    }

                    //json.Add("url", HttpUtility.UrlEncode(filenames));
                    if (Request.Headers["auth"] == null && Request.Url.Host.ToLower() != Request.UrlReferrer.Host.ToLower())
                    {
                        string postdata = json.ToJson().Replace("/", "0x2f").Replace("+", "0x2b").Replace(" ", "0x20");
                        postdata = HttpUtility.UrlEncode(postdata);
                        Response.Redirect("http://" + Request.UrlReferrer.Host + "/Plugins/ProUpload.aspx?postdata=" + postdata, true);
                    }
                    else
                    {
                        //eBase.WriteJson(json); //IE解析有问题：文档的顶层无效
                        Response.Clear();
                        Response.Write(json.ToJson());
                        Response.End();
                    }
                    Response.End();

                }
                #endregion
                #region 编辑器-Flash上传
                if (Request.QueryString["type"].ToLower() == "flash")
                {
                    HttpPostedFile file = Request.Files["flaFile"];
                    if (file == null) showError("请选择文件。");
                    if (file.InputStream.Length == 0) showError("请选择文件!");// showError(f.InputStream.Length.ToString());





                    string ext = file.FileName.fileExtension();
                    string filename = eBase.GetFileName() + ext;
                    string pathname = tempPath + filename;
                    while (File.Exists(pathname))
                    {
                        filename = eBase.GetFileName() + ext;
                        pathname = tempPath + filename;
                    }
                    if (!Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath);
                    file.safeSaveAs(pathname);


                    if (eConfig.saveSource())
                    {
                        if (!Directory.Exists(sourcePath)) Directory.CreateDirectory(sourcePath);
                        string _pathname = sourcePath + filename;
                        file.safeSaveAs(_pathname);
                    }


                    #region 日志
                    if (writeLog)
                    {
                        eTable etb = new eTable("a_eke_sysErrors");
                        etb.Fields.Add("Message", "upload");
                        JsonData _json = new JsonData();
                        _json.Add("filename", file.FileName);
                        _json.Add("size", file.ContentLength.ToString());
                        _json.Add("path", "upload/" + string.Format("{0:yyyy/MM/dd}", DateTime.Now) + "/" + filename);
                        etb.Fields.Add("StackTrace", _json.ToJson());
                        //etb.Add();
                    }
                    #endregion

                    //filename = ePicture.AutoHandle(pathname, PictureMaxWidth);

                    filename = backPath + filename;
                    //if (fileExt == ".bmp" || fileExt == ".tif" || fileExt == ".jpeg" || fileExt == ".png")

                    string id = Request["id"].Trim();           //kindeditor控件的id
                    //string title = Path.GetFileName(f.FileName).Trim();   //文件名称（原文件名）
                    //string ext = fileExt.Substring(1).ToLower().Trim(); //文件后缀名

                    string w = Request["flaWidth"].Trim();
                    string h = Request["flaHeight"].Trim();
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    Response.Charset = "UTF-8";
                    sb.Append("<html>");
                    sb.Append("<head>");
                    sb.Append("<title>Insert Flash</title>");
                    sb.Append("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">");
                    sb.Append("</head>");
                    sb.Append("<body>");
                    sb.Append("<script type=\"text/javascript\">parent.KE.plugin[\"newflash\"].insert(\"" + id + "\", \"" + filename + "\",\"" + w + "\",\"" + h + "\");</script>");
                    sb.Append("</body>");
                    sb.Append("</html>");

                    if (Request.Url.Host.ToLower() != Request.UrlReferrer.Host.ToLower())
                    {
                        string postdata = "<script type=\"text/javascript\">parent.KE.plugin[\"newmedia\"].insert(\"" + id + "\", \"" + filename + "\",\"" + w + "\",\"" + h + "\");</script>";
                        postdata = postdata.Replace("/", "0x2f").Replace("+", "0x2b").Replace(" ", "0x20");
                        postdata = HttpUtility.UrlEncode(postdata);
                        Response.Redirect("http://" + Request.UrlReferrer.Host + "/Plugins/ProUpload.aspx?postdata=" + postdata, true);
                    }
                    else
                    {
                        Response.Write(sb.ToString());
                    }
                    Response.End();
                }
                #endregion
                #region 编辑器-媒体上传
                if (Request.QueryString["type"].ToLower() == "media")
                {
                    HttpPostedFile file = Request.Files["flaFile"];
                    if (file == null) showError("请选择文件。");
                    if (file.InputStream.Length == 0) showError("请选择文件!");
                    string ext = file.FileName.fileExtension();
                    string filename = eBase.GetFileName() + ext;
                    string pathname = tempPath + filename;
                    while (File.Exists(pathname))
                    {
                        filename = eBase.GetFileName() + ext;
                        pathname = tempPath + filename;
                    }
                    if (!Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath);
                    file.safeSaveAs(pathname);

                    if (eConfig.saveSource())
                    {
                        if (!Directory.Exists(sourcePath)) Directory.CreateDirectory(sourcePath);
                        string _pathname = sourcePath + filename;
                        file.safeSaveAs(_pathname);
                    }

                    #region 日志
                    if (writeLog)
                    {
                        eTable etb = new eTable("a_eke_sysErrors");
                        etb.Fields.Add("Message", "upload");
                        JsonData _json = new JsonData();
                        _json.Add("filename", file.FileName);
                        _json.Add("size", file.ContentLength.ToString());
                        _json.Add("path", "upload/" + string.Format("{0:yyyy/MM/dd}", DateTime.Now) + "/" + filename);
                        etb.Fields.Add("StackTrace", _json.ToJson());
                        //etb.Add();

                    }
                    #endregion

                    //filename = ePicture.AutoHandle(pathname, PictureMaxWidth);
                    //filename = "../upload/temp/" + filename;
                    filename = backPath + filename;
                    //if (fileExt == ".bmp" || fileExt == ".tif" || fileExt == ".jpeg" || fileExt == ".png")

                    string id = Request["id"].Trim();           //kindeditor控件的id
                    //string title = Path.GetFileName(f.FileName).Trim();   //文件名称（原文件名）
                    //string ext = fileExt.Substring(1).ToLower().Trim(); //文件后缀名

                    string w = Request["flaWidth"].Trim();
                    string h = Request["flaHeight"].Trim();
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    Response.Charset = "UTF-8";
                    sb.Append("<html>");
                    sb.Append("<head>");
                    sb.Append("<title>Insert Media</title>");
                    sb.Append("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">");
                    sb.Append("</head>");
                    sb.Append("<body>");
                    sb.Append("<script type=\"text/javascript\">parent.KE.plugin[\"newmedia\"].insert(\"" + id + "\", \"" + filename + "\",\"" + w + "\",\"" + h + "\");</script>");
                    sb.Append("</body>");
                    sb.Append("</html>");
                    Response.Write(sb.ToString());
                    Response.End();
                }
                #endregion
                #region 编辑器-附件上传
                if (Request.QueryString["type"].ToLower() == "accessory")
                {
                    HttpPostedFile file = Request.Files["imgFile"];
                    if (file == null) showError("请选择文件。");
                    if (file.InputStream.Length == 0) showError("请选择文件!");
                    string ext = file.FileName.fileExtension();
                    string filename = eBase.GetFileName() + ext;
                    string pathname = tempPath + filename;
                    while (File.Exists(pathname))
                    {
                        filename = eBase.GetFileName() + ext;
                        pathname = tempPath + filename;
                    }
                    if (!Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath);
                    file.safeSaveAs(pathname);
                    if (eConfig.saveSource())
                    {
                        if (!Directory.Exists(sourcePath)) Directory.CreateDirectory(sourcePath);
                        string _pathname = sourcePath + filename;
                        file.safeSaveAs(_pathname);
                    }

                    #region 日志
                    if (writeLog)
                    {
                        eTable etb = new eTable("a_eke_sysErrors");
                        etb.Fields.Add("Message", "upload");
                        JsonData _json = new JsonData();
                        _json.Add("filename", file.FileName);
                        _json.Add("size", file.ContentLength.ToString());
                        _json.Add("path", "upload/" + string.Format("{0:yyyy/MM/dd}", DateTime.Now) + "/" + filename);
                        etb.Fields.Add("StackTrace", _json.ToJson());
                        //etb.Add();
                    }
                    #endregion


                    //filename = ePicture.AutoHandle(pathname, PictureMaxWidth);
                    //filename = "../upload/temp/" + filename;
                    filename = backPath + filename;
                    //if (fileExt == ".bmp" || fileExt == ".tif" || fileExt == ".jpeg" || fileExt == ".png")

                    string id = Request["id"].Trim();           //kindeditor控件的id
                    string title = Path.GetFileName(file.FileName).Trim();   //文件名称（原文件名）
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    Response.Charset = "UTF-8";
                    sb.Append("<html>");
                    sb.Append("<head>");
                    sb.Append("<title>Insert Accessory</title>");
                    sb.Append("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">");
                    sb.Append("</head>");
                    sb.Append("<body>");
                    sb.Append("<script type=\"text/javascript\">parent.KE.plugin[\"accessory\"].insert(\"" + id + "\", \"" + filename + "\",\"" + title + "\",\"" + ext.Substring(1) + "\");</script>");
                    sb.Append("</body>");
                    sb.Append("</html>");

                    if (Request.Url.Host.ToLower() != Request.UrlReferrer.Host.ToLower())
                    {
                        string postdata = "<script type=\"text/javascript\">parent.KE.plugin[\"accessory\"].insert(\"" + id + "\", \"" + filename + "\",\"" + title + "\",\"" + ext.Substring(1) + "\");</script>";
                        postdata = postdata.Replace("/", "0x2f").Replace("+", "0x2b").Replace(" ", "0x20");
                        postdata = HttpUtility.UrlEncode(postdata);
                        Response.Redirect("http://" + Request.UrlReferrer.Host + "/Plugins/ProUpload.aspx?postdata=" + postdata, true);
                    }
                    else
                    {
                        Response.Write(sb.ToString());
                    }
                    Response.End();
                }
                #endregion
            }
            #endregion
            if (Request.QueryString["act"] != null)
            {
                #region 获取大小
                if (Request.QueryString["act"].ToLower() == "getsize")
                {
                    string filename = Request.QueryString["file"].ToString();
                    int ow = 0;
                    int oh = 0;
                    if (filename.ToLower().StartsWith("http"))
                    {
                        filename = filename.Replace(eBase.getBaseURL(), "");
                    }

                    string ext = filename.fileExtension();
                    if (!eConfig.allowExtensions.Contains(ext))
                    {
                        filename = basePath + filename.Replace("../", "").Replace("/", "\\");
                        if (System.IO.File.Exists(filename))
                        {
                            try
                            {
                                System.Drawing.Image img = System.Drawing.Image.FromFile(filename);
                                ow = img.Width;
                                oh = img.Height;
                                img.Dispose();
                            }
                            catch { }
                        }
                    }
                    JsonData json = new JsonData();
                    json.Add("width", ow.ToString());
                    json.Add("height", oh.ToString());
                    eResult.WriteJson(json);

                }
                #endregion
                #region 下载网络文件
                if (Request.QueryString["act"].ToLower() == "down")
                {
                    JsonData json = new JsonData();
                    string file = Request.QueryString["file"].ToString();
                    //string[] arr = file.Split(".".ToCharArray());
                    //string ext = "." + arr[arr.Length - 1];
                    string ext = file.fileExtension();
                    if (eConfig.PreventExtensions.Contains(ext))
                    {
                        json.Add("url", "");
                    }
                    else
                    {
                        string virtualDir = eConfig.UploadPath();
                        string _basePath = basePath;
                        _basePath += virtualDir.Replace("/", "\\");
                        if (!Directory.Exists(_basePath)) Directory.CreateDirectory(_basePath);

                        string filename = eBase.GetFileName() + ext;
                        string pathname = _basePath + filename;
                        while (File.Exists(pathname))
                        {
                            filename = eBase.GetFileName() + ext;
                            pathname = _basePath + filename;
                        }

                      
                        System.Net.WebClient wc = new System.Net.WebClient();
                        try
                        {
                            wc.DownloadFile(file, pathname);
                            wc.Dispose();
                            json.Add("url", eBase.getBaseURL() + virtualDir + filename);

                        }
                        catch
                        {
                            json.Add("url", file);
                        }
                    }
                    eResult.WriteJson(json);
                }
                #endregion
                #region 删除正式文件
                if (Request.QueryString["act"].ToLower() == "deltrue")
                {
                    string filename = Request.QueryString["file"].ToString();
                    filename = Regex.Replace(filename, eBase.getBaseURL(), "", RegexOptions.IgnoreCase);
                    filename = basePath + filename.Replace("../", "").Replace("/", "\\");
                    //if (filename.ToLower().IndexOf("/filemanage/") == -1 && filename.ToLower().IndexOf("/templates/") == -1)
                    if (filename.ToLower().IndexOf("/temp/") > -1)
                    {
                        try
                        {
                            //System.IO.File.Delete(filename);
                            //System.IO.File.Delete(filename.Replace(".", "_sm."));
                        }
                        catch
                        {
                        }
                    }
                    Response.End();
                }
                #endregion
                #region 临时文件移动到正式文件夹下
                if (Request.QueryString["act"].ToLower() == "move")
                {
                    string file = Request.QueryString["file"].ToString();
                    file = Regex.Replace(file, eBase.getBaseURL(), "", RegexOptions.IgnoreCase);
                    string _basePath = basePath;
                    string temppath = _basePath + file.Replace("/", "\\");
                    JsonData json = new JsonData();
                    if (File.Exists(temppath) && file.ToLower().IndexOf("/temp/") > -1)
                    {
                        string[] arr = temppath.Split("\\".ToCharArray());
                        string filename = arr[arr.Length - 1];
                        string virtualDir = eConfig.UploadPath();
                        _basePath += virtualDir.Replace("/", "\\");
                        if (!Directory.Exists(_basePath)) Directory.CreateDirectory(_basePath);
                        string newpath = _basePath + filename;
                        File.Move(temppath, newpath);
                        //eBase.Writeln("newpath1:" + virtualDir + filename);
                        json.Add("url", eBase.getBaseURL() + virtualDir + filename);
                    }
                    else
                    {
                        json.Add("url", file);
                    }

                    Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
                    Response.Write(json.ToJson());
                    Response.End();
                }
                #endregion
                #region 上传完成
                if (Request.QueryString["act"].ToLower() == "finsh")
                {
                    if (Request.QueryString["sub"] != null) Response.Write("<script>﻿try{parent.document.getElementById('" + Request.QueryString["obj"].ToString() + "').value='" + Request.QueryString["file"].ToString() + "';}catch(e){}</script>");


                    Response.Write("<font color='#009900'>上传成功!</font><a style='line-height:22px;display:inline-block;margin-left:10px;margin-right:18px;text-decoration:none;' href='?act=del&obj=" + Request.QueryString["obj"].ToString() + "&PictureMaxWidth=" + PictureMaxWidth.ToString() + "&file=" + Request.QueryString["file"].ToString() + "' onclick='return del();'><font color='#FF0000'>删除重新上传?</font></a>");
                    string filename = Request.QueryString["file"].ToString();
                    if (filename.ToLower().IndexOf("http") > -1)
                    {
                        filename = filename.Replace(eBase.getBaseURL(), "");
                    }
                    string ext = filename.fileExtension();
                    if(eConfig.allowExtensions.Contains(ext))
                    {
                        int ow = 0;
                        int oh = 0;
                        if (Request.QueryString["ow"] != null) ow = Convert.ToInt32(Request.QueryString["ow"].ToString());
                        if (Request.QueryString["oh"] != null) oh = Convert.ToInt32(Request.QueryString["oh"].ToString());
                        filename = basePath + filename.Replace("../", "").Replace("/", "\\");
                        if (System.IO.File.Exists(filename))
                        {
                            try
                            {
                                System.Drawing.Image img = System.Drawing.Image.FromFile(filename);
                                ow = img.Width;
                                oh = img.Height;
                                img.Dispose();
                            }
                            catch { }
                        }
                        else
                        {
                            if (accUrl.Length > 0)
                            {
                                string url = accUrl + "Plugins/ProUpload.aspx?act=getsize&obj=" + Request.QueryString["obj"].ToString() + "&PictureMaxWidth=" + PictureMaxWidth.ToString() + "&file=" + Request.QueryString["file"].ToString();
                                string result = eBase.getRequest(url);
                                if (result.StartsWith("{"))
                                {
                                    //eJson json = new eJson(result);
                                    JsonData json = result.ToJsonData();
                                    ow = Convert.ToInt32(json.GetValue("width"));
                                    oh = Convert.ToInt32(json.GetValue("height"));
                                }

                            }
                        }
                        if (ow > 0)
                        {
                            Response.Write("<img src=\"" + eBase.getAbsolutePath() + "images/view.jpg\" width=\"12\" height=\"12\" style=\"cursor:pointer;\" alt=\"查看图片\" onclick=\"parent.viewImage('" + Request.QueryString["file"].ToString() + "'," + ow.ToString() + "," + oh.ToString() + ");\" align=\"absmiddle\" />");
                        }
                        /*
                    else
                    {
                        ow = 400;
                        oh = 300;
                        Response.Write("<img src=\"" + eBase.getAbsolutePath() + "images/view.jpg\" width=\"12\" height=\"12\" style=\"cursor:pointer;\" alt=\"查看图片\" onclick=\"parent.viewImage('" + Request.QueryString["file"].ToString() + "'," + ow.ToString() + "," + oh.ToString() + ");\" align=\"absmiddle\" />");
                    }
                    */
                    }
                }
                #endregion
                #region 删除临时文件
                if (Request.QueryString["act"].ToLower() == "del")
                {

                    string filename = Request.QueryString["file"].ToString();
                    filename = Regex.Replace(filename, eBase.getBaseURL(), "", RegexOptions.IgnoreCase);
                    filename = basePath + filename.Replace("../", "").Replace("/", "\\");


                    //只删除临时文件，防止删除正式文件且不保存。
                    if (filename.ToLower().IndexOf("\\temp\\") > -1 && !filename.ToLower().StartsWith("http"))
                    {
                        //System.IO.File.Exists
                        try
                        {
                            eFileHelper.removeFileCache(filename);//删除查看缓存文件
                            System.IO.File.Delete(filename);
                            System.IO.File.Delete(filename.Replace(".", "_sm."));
                            System.IO.File.Delete(filename.Replace("_thumb", ""));

                            #region 源文件处理
                            eFileInfo fi = new eFileInfo(filename);
                            filename = sourcePath + fi.FullName;
                            if (File.Exists(filename))
                            {
                                System.IO.File.Delete(filename);
                            }
                            #endregion
                        }
                        catch
                        {
                        }
                    }
                    if (filename.IndexOf("_thumb") > -1) Response.End();
                    if (Request.QueryString["obj"] != null)
                    {
                        if (accUrl.Length > 0)
                        {
                            string url = accUrl + "Plugins/ProUpload.aspx?act=del&obj=" + Request.QueryString["obj"].ToString() + "&PictureMaxWidth=" + PictureMaxWidth.ToString() + "&file=" + Request.QueryString["file"].ToString();
                            string result = eBase.getRequest(url);
                            Response.Write("<script>﻿try{parent.document.getElementById('" + Request.QueryString["obj"].ToString() + "').value='';}catch(e){}\r\ndocument.location='" + accUrl + "Plugins/ProUpload.aspx?obj=" + Request.QueryString["obj"].ToString() + "&PictureMaxWidth=" + PictureMaxWidth.ToString() + "';</script>");
                        }
                        else
                        {
                            Response.Write("<script>﻿try{parent.document.getElementById('" + Request.QueryString["obj"].ToString() + "').value='';}catch(e){}\r\ndocument.location='ProUpload.aspx?obj=" + Request.QueryString["obj"].ToString() + "&PictureMaxWidth=" + PictureMaxWidth.ToString() + "';</script>");
                        }
                    }
                    Response.End();
                }
                #endregion
            }
            if (Request.Form["act"] != null)
            {
                #region 保存文件,上传控件,OK
                HttpPostedFile f = imgFile.PostedFile;
                if (f.ContentLength > 0)
                {
                    string ext = f.FileName.fileExtension();
                    if (1 == 1)//if (".gif.jpg.bmp.flv".IndexOf(postFileName) > -1)
                    {
                        string filename = eBase.GetFileName() + ext;
                        string pathname = tempPath + filename;
                        while (File.Exists(pathname))
                        {
                            filename = eBase.GetFileName() + ext;
                            pathname = tempPath + filename;
                        }
                        if (!Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath);
                        f.safeSaveAs(pathname);
                        if (eConfig.saveSource())
                        {
                            if (!Directory.Exists(sourcePath)) Directory.CreateDirectory(sourcePath);
                            string _pathname = sourcePath + filename;
                            f.safeSaveAs(_pathname);
                        }

                        filename = ePicture.AutoHandle(pathname, PictureMaxWidth);
                        int ow = 0;
                        int oh = 0;
                        //string allExt = ".gif.jpg.jpeg.bmp.png";
                       // if (allExt.IndexOf(postFileName.ToLower()) > -1)
                        if(eConfig.allowExtensions.Contains(ext))
                        {
                            try
                            {
                                System.Drawing.Image img = System.Drawing.Image.FromFile(pathname);
                                ow = img.Width;
                                oh = img.Height;
                                img.Dispose();
                            }
                            catch { }
                        }
                        #region 日志
                        if (writeLog)
                        {
                            eTable etb = new eTable("a_eke_sysErrors");
                            etb.Fields.Add("Message", "upload");
                            JsonData _json = new JsonData();
                            _json.Add("filename", f.FileName);
                            _json.Add("size", f.ContentLength.ToString());
                            _json.Add("path", "upload/" + string.Format("{0:yyyy/MM/dd}", DateTime.Now) + "/" + filename);
                            etb.Fields.Add("StackTrace", _json.ToJson());
                            etb.Add();
                        }
                        #endregion


                        filename = backPath + filename;


                        if (Request.Form["formhost"].ToString().Length > 0)
                        {
                            Response.Redirect("http://" + Request.Form["formhost"].ToString() + "/Plugins/ProUpload.aspx?act=finsh&sub=true&obj=" + Request.QueryString["obj"].ToString() + "&PictureMaxWidth=" + PictureMaxWidth.ToString() + "&file=" + filename + "&ow=" + ow.ToString() + "&oh=" + oh.ToString(), true);
                        }
                        else
                        {
                            Response.Write("<script>try{eval(\"parent.document.getElementById('" + Request.QueryString["obj"].ToString() + "').value='" + filename + "';\")}catch(e){}</script>");
                            Response.Write("<script>document.location='?act=finsh&obj=" + Request.QueryString["obj"].ToString() + "&PictureMaxWidth=" + PictureMaxWidth.ToString() + "&file=" + filename + "';</script>");
                        }
                        Response.End();
                    }
                    /*
                else
                {
                    Response.Write("<script>alert('不支持的文件类型!');document.location='?obj=" + Request.QueryString["obj"].ToString() + "';</script>");
                    Response.End();
                }
                */
                }
                #endregion
            }
        }
        private void showError(string message)
        {
            JsonData json = new JsonData();
            json.Add("errcode", "1");
            json.Add("message", message);
            Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
            Response.Write(json.ToJson());
            Response.End();

        }
    }
}